﻿using MLSMooc.Helper;
using MLSMooc.Session.Interface;
using MLSMooc.Session.Model;
using System;
using System.Threading.Tasks;

namespace MLSMooc.Session.Implement
{
    public class SessionUserService : ISessionService<SessionUser>
    {
        private static SessionUserService _inatance = new SessionUserService();

        private SessionUserService() { }

        public static SessionUserService GetInstance() => _inatance;

        public SessionUser DeSerializeDecrypt(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                try
                {
                    string json = str.ToAESDecrypt();
                    SessionUser sessionUser = SerializeHelper.DeSerializeObject<SessionUser>(json);
                    return sessionUser;
                }
                catch (Exception)
                {
                    return null;
                }
            }
            return null;
        }

        /// <summary>
        /// 解密并反序列化
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public Task<SessionUser> DeSerializeDecryptAsync(string str)
        {
            return Task.Run(() =>
            {
                if (!string.IsNullOrEmpty(str))
                {
                    try
                    {
                        string json = str.ToAESDecrypt();
                        SessionUser sessionUser = SerializeHelper.DeSerializeObject<SessionUser>(json);
                        return sessionUser;
                    }
                    catch (Exception)
                    {
                        return null;
                    }
                }
                return null;
            });
        }

        public string EnSerializeEncrypt(SessionUser sessionUser)
        {
            string res = string.Empty;
            if (sessionUser != null && sessionUser.Id != 0)
            {
                string json = SerializeHelper.SerializeJson(sessionUser);
                res = json.ToAESEncrypt();
            }
            return res;
        }

        /// <summary>
        /// 序列化并加密
        /// </summary>
        /// <param name="sessionUser"></param>
        /// <returns></returns>
        public Task<string> EnSerializeEncryptAsync(SessionUser sessionUser)
        {
            return Task.Run(() =>
            {
                string res = string.Empty;
                if (sessionUser != null && sessionUser.Id != 0)
                {
                    string json = SerializeHelper.SerializeJson(sessionUser);
                    res = json.ToAESEncrypt();
                }
                return res;
            });
        }
    }
}